﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SL.WorkfowDesigner.Designer;
using SL.WorkfowDesigner.Utilities;
using SL.WorkfowDesigner.ViewModels;

namespace SL.WorkfowDesigner
{
    public partial class MainPage : UserControl
    {
        //ZIndex 管理 ： 0-1000 预留 
        //              1000 - 2000 底板 GridLine rule 预留位置
        //              1200 底板
        //              2000 - 6000 拖拽物
        //              2000 - 5000 形状ZIndex管理
        //              9000 - 10000 预留


        private static int ZIndex_GridLine = 1500;
        private static int ZIndex_Paper = 1200;
        private static int Grid_Margin_X = 20;
        private static int Grid_Margin_Y = 20;
        private bool _initializeComponentFinished = false;

        private DesignerZIndexManager zIndexManager = new DesignerZIndexManager(2000,6000);

        private DesignerPanManager panManager;
 
        

        public MainPage()
        {            
            InitializeComponent();
            _initializeComponentFinished = true;
            this.DataContext = new MainLayoutViewModel();
            SetGrid();

            panManager = new DesignerPanManager(this.FreeLayout,this.FreeLayoutScrollViewer,this.scaleTransform,this.DataContextEntity.EnablePanZoom);
        }



        public MainLayoutViewModel DataContextEntity
        {
            get { return this.DataContext as MainLayoutViewModel; }
        }

        void SetGrid()
        {
            for (int i = 0; i < this.DataContextEntity.VerticalGridCounts; i++)
                this.FreeLayout.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });

            for (int i = 0; i < this.DataContextEntity.HorizontalGridCounts; i++)
                this.FreeLayout.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

            for (int i = 0; i < this.DataContextEntity.VerticalGridCounts; i++)
            {
                for (int j = 0; j < this.DataContextEntity.HorizontalGridCounts; j++)
                {
                    var r = new Rectangle();
                    r.Stroke = new SolidColorBrush(Color.FromArgb(150, 0, 0, 0));
                    r.StrokeThickness = 0.5;
                    Binding binding = new Binding("ShowGridLines");
                    binding.Converter = new VisibilityConverter();
                    binding.Mode = BindingMode.OneWay;
                    r.SetBinding(Rectangle.VisibilityProperty, binding);

                    r.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    r.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                    
                    this.FreeLayout.Children.Add(r);
                    Grid.SetRow(r, i);
                    Grid.SetColumn(r, j);
                    Canvas.SetZIndex(r, ZIndex_GridLine); 

                    this.FreeLayout.UpdateLayout();
                }
            }

            var rPaper = new Rectangle();
            rPaper.Stroke = new SolidColorBrush(Colors.Black);
            rPaper.StrokeThickness = 1;
 
            rPaper.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            rPaper.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

            rPaper.Fill = new SolidColorBrush(Colors.White);

            DropShadowEffect dropShadowEffect = new DropShadowEffect();
            dropShadowEffect.BlurRadius = 5;
            dropShadowEffect.Color = Colors.Black;
            dropShadowEffect.Direction = 315;
            dropShadowEffect.Opacity = 0.6;
            dropShadowEffect.ShadowDepth = 9;
            rPaper.Effect = dropShadowEffect;


            this.FreeLayout.Children.Add(rPaper);
            Grid.SetRow(rPaper, 0);
            Grid.SetColumn(rPaper, 0);
            Grid.SetColumnSpan(rPaper, this.DataContextEntity.HorizontalGridCounts);
            Grid.SetRowSpan(rPaper, this.DataContextEntity.VerticalGridCounts);
            Canvas.SetZIndex(rPaper, ZIndex_Paper);
            this.FreeLayout.UpdateLayout();
        }

        private void btnReset_OnClick(object sender, RoutedEventArgs e)
        {
            this.DataContextEntity.ZoomLevelValue = 100;
            layoutTransform.ApplyLayoutTransform();
        }

        private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
        {
        }

        private void btnAdd_OnClick(object sender, RoutedEventArgs e)
        {
            var r = new Rectangle();
            r.Fill = new SolidColorBrush(Color.FromArgb(255,50,60,210));

            r.Stroke = new SolidColorBrush(Colors.Black);
            r.StrokeThickness = 1;
 
            r.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            r.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;

            int timeIndex = System.DateTime.Now.Ticks.GetHashCode();

            int x = new Random(timeIndex).Next(1, this.FreeLayout.ColumnDefinitions.Count -1);
            int y = new Random(timeIndex).Next(1, this.FreeLayout.RowDefinitions.Count - 1);
            int width = new Random(timeIndex).Next(1, this.FreeLayout.ColumnDefinitions.Count - x);
            int heigth = new Random(timeIndex).Next(1, this.FreeLayout.RowDefinitions.Count - y);

            this.FreeLayout.Children.Add(r);
            Grid.SetRow(r, x);
            Grid.SetColumn(r, y);
            Grid.SetColumnSpan(r, width);
            Grid.SetRowSpan(r, heigth);
            int zindex = zIndexManager.AddElement(r);
            Canvas.SetZIndex(r, zindex);



            this.FreeLayout.UpdateLayout();
        }

        private void btnDownload_OnClick(object sender, RoutedEventArgs e)
        {
            var img = new WriteableBitmap(FreeLayout, null);

            if (img != null)
            {
                SaveFileDialog saveDlg = new SaveFileDialog();
                saveDlg.DefaultFileName = "workflowdesigner.jpg";
                saveDlg.Filter = "JPEG File (*.jpeg)|*.jpeg";
                saveDlg.DefaultExt = ".jpeg";

                if ((bool)saveDlg.ShowDialog())
                {
                    using (Stream fs = saveDlg.OpenFile())
                    {
                        MemoryStream stream = WriteableBitmapHelper.GetImageStream(img);

                        byte[] binaryData = new Byte[stream.Length];
                        long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
                        fs.Write(binaryData, 0, binaryData.Length);
                    }
                }
            }
        }

 

        private void btnPrint_OnClick(object sender, RoutedEventArgs e)
        {
             //DesignerPrintManager designerPrint = new DesignerPrintManager(FreeLayout,silderZoom);

             //designerPrint.Print("WorkFlowDesigner");
        }

        private void FreeLayout_OnLayoutUpdated(object sender, EventArgs e)
        {
            double gridActualHeight = 0;
            double gridActualWidth = 0;

            foreach (var rowDefinition in FreeLayout.RowDefinitions)
            {
                gridActualHeight += rowDefinition.ActualHeight;
            }

            foreach (var colDefinition in FreeLayout.ColumnDefinitions)
            {
                gridActualWidth += colDefinition.ActualWidth;
            }

 
        }

        private void silderZoom_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (_initializeComponentFinished)
            {
                scaleTransform.ScaleX = silderZoom.Value / 100d;
                scaleTransform.ScaleY = silderZoom.Value / 100d;
                layoutTransform.ApplyLayoutTransform();
            }
        }

        private void LayoutRoot_OnLayoutUpdated(object sender, EventArgs e)
        {
            DataContextEntity.HorizontalGridActualWidth = LayoutRoot.ColumnDefinitions[1].ActualWidth - Grid_Margin_X;
            DataContextEntity.VerticalGridActualHeight = LayoutRoot.RowDefinitions[1].ActualHeight - Grid_Margin_Y;

            if (DataContextEntity.HorizontalGridActualWidth <= 0)
                return;
            if (DataContextEntity.VerticalGridActualHeight <= 0)
                return;

            this.FreeLayout.Width = DataContextEntity.HorizontalGridActualWidth;
            this.FreeLayout.Height = DataContextEntity.VerticalGridActualHeight;

        }

        private void chkEnablePanZoom_Click(object sender, RoutedEventArgs e)
        {
            panManager.EnablePanZoom = this.DataContextEntity.EnablePanZoom;
        }
    }
}
